package com.health.utils;

import com.alibaba.fastjson.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 七牛云-文件处理
 */
public class QiNiuUtil {

    private static final String ACCESSKEY = "gyBO2bpXAa03yX9o84zP7ymdJSbjRPnc6PFi6lXv";
    private static final String SECRETKEY = "kFTDw3q-7wLwq7CYyJmBo2YwFkLTKTunKF8oOTOM";
    private static final String BUCKET = "health-setmeal-2img";
    public static final String DOMAIN = "http://qowq28clr.hn-bkt.clouddn.com/";

    /**
     * 上传文件
     */
    public static String uploadFile(InputStream inputStream) throws QiniuException {
        //授权
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);
        //获得指定空间的令牌
        String upToken = auth.uploadToken(BUCKET);

        //根据指定的配置，创建一个上传管理器
        Configuration cfg = new Configuration(Region.region2());
        UploadManager uploadManager = new UploadManager(cfg);

        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;

        //上传文件
        Response response = uploadManager.put(inputStream,key,upToken,null, null);
        //解析上传成功的结果
        DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);

        //获取文件名
        return putRet.key;
    }

    /**
     * 文件列表
     */
    public static List<String> fileList(){
        BucketManager bucketManager = getBucketManager();

        //列举空间文件列表, 第一个参数：图片的空间名,第二个参数，文件名前缀过滤。“”代理所有
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(BUCKET,"");

        List<String> fileList = new ArrayList<>();
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                // item.key 文件名
                fileList.add(item.key);
            }
        }
        return fileList;
    }

    /**
     * 批量删除文件
     */
    public static void deleteFile(String[] keys) throws QiniuException {
        BucketManager bucketManager = getBucketManager();

        //创建批处理器
        BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
        //批量删除多个文件
        batchOperations.addDeleteOp(BUCKET,keys);
        bucketManager.batch(batchOperations);
    }

    /**
     * 获取空间管理器
     */
    private static BucketManager getBucketManager(){
        //授权
        Auth auth = Auth.create(ACCESSKEY, SECRETKEY);

        //根据指定的配置，创建一个空间管理器
        Configuration cfg = new Configuration(Region.region2());
        return new BucketManager(auth, cfg);
    }
}